package com.example.qihuibao.module.main

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import com.example.qihuibao.base.BaseActivity
import com.example.qihuibao.constant.Config
import com.example.qihuibao.databinding.ActivityMainBinding
import com.example.qihuibao.module.service.TimerService
import com.example.qihuibao.utils.ConnectUtil
import com.example.qihuibao.utils.LogUtil

class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {

    private var timerServiceConnection:ServiceConnection? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        startTimerService()
        viewBinding.tvCode.setOnClickListener {
            Thread {
                ConnectUtil.groupSend()
            }.start()
        }
    }

    override fun onResume() {
        super.onResume()
        getQRCode {
            viewBinding.tvCode.text = "main:$it"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timerServiceConnection != null) {
            unbindService(timerServiceConnection!!)
        }
    }

    private fun startTimerService() {
        timerServiceConnection = object:ServiceConnection{
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
//                val binder: NetworkStatusService.MyBinder = service as NetworkStatusService.MyBinder
                val binder:TimerService.MyBinder = service as TimerService.MyBinder
                binder.getService().setCallback(object:TimerService.CallBack{
                    override fun scheduledTasks() {
                        secondTimer()
                    }
                })
            }

            override fun onServiceDisconnected(name: ComponentName?) {
            }
        }
        val intent = Intent(this, TimerService::class.java)
        bindService(intent, timerServiceConnection!!, BIND_AUTO_CREATE)
        startService(intent)
    }

    private fun secondTimer() {
        LogUtil.e("secondTimer")
        if (Config.isServerStation) {

        }
    }
}